package com.czk.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.czk.springcloud.entity.CommonResult;
import com.czk.springcloud.entity.Payment;
import com.czk.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/12/23 21:22
 */
@RestController
@Slf4j
@RequestMapping("/consumer")
public class OrderNacosController {
    @Resource
    private RestTemplate restTemplate;
    @Value("${service-url.nacos-user-service}")
    private String serverURL;

    @GetMapping("/payment/nacos/{id}")
    public String paymentInfo(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(serverURL + "/payment/nacos/" + id, String.class);
    }

    /**
     * 注入feign客户端
     */
    @Autowired
    private PaymentService paymentService;

    @GetMapping("/feign/{id}")
    public CommonResult<Payment> testFeign(@PathVariable("id") Long id) {
        CommonResult<Payment> result = paymentService.paymentSql(id);
        if (result.getData().getId() == 4) {
            throw new RuntimeException("id错误");
        } else {
            return result;
        }
    }

    public static final String SERVICE_URL = "http://nacos-payment-provider";

    /**
     * 测试服务降级
     *
     * @param id
     * @return
     */
    @GetMapping("/rest/{id}")
    @SentinelResource(value = "testRestTemplate", fallback = "fallBack", blockHandler = "block")
    public CommonResult<Payment> testRestTemplate(@PathVariable Long id) {
        // 拿到结果值
        CommonResult commonResult = restTemplate.getForObject(SERVICE_URL + "/payment/sql/" + id, CommonResult.class, id);
        if (id == 4) {
            throw new IllegalArgumentException("非法参数异常");
        } else if (commonResult.getData() == null) {
            throw new NullPointerException("空指针异常");
        }
        return commonResult;
    }

    /**
     * 服务降级的方法
     *
     * @param id
     * @param throwable
     * @return
     */
    public CommonResult fallBack(@PathVariable Long id, Throwable throwable) {
        return new CommonResult(444, "参数错误" + throwable.getMessage(), new Payment(4L, UUID.randomUUID().toString()));
    }
}
